package com.aliyun.heiyu.powermaster.server.dao.impl;

import com.aliyun.heiyu.common.util.*;
import com.aliyun.heiyu.powermaster.proto.AirSiteBasalData;
import com.aliyun.heiyu.powermaster.server.dao.AiDataProviderDao;
import com.aliyun.heiyu.powermaster.server.dao.entity.AiDataEntity;
import com.aliyun.heiyu.powermaster.server.dao.entity.AirSiteBasalEntity;
import com.aliyun.heiyu.powermaster.server.dao.entity.DataSign;


import java.util.*;


public class AiDataProviderDaoImpl implements AiDataProviderDao {
        String baseColumn = "id,collect_time,current_temp,reference_temp,ip,power,control_status";
        String server="server";

    @Override
    public boolean insert(Date collect_time,double current_temp,double reference_temp,int control_status,double save_power,double risk_value ) {
        String sql = "insert into ai_information(collect_time,current_temp,reference_temp,control_status,save_power,risk_value) values (?,?,?,?,?,?)";
        Object[] kk = new Object[6];
        kk[0] = collect_time;
        kk[1] = current_temp;
        kk[2] =reference_temp;
        kk[3] =control_status;
        kk[4] =save_power;
        kk[5] =risk_value;
        boolean result = JdbcUtil.update(sql, kk);
        return result;
    }

    @Override
    public List<AiDataEntity> findAll() {
        String sql = "select "+baseColumn+" from ai_history_info";
        List<AiDataEntity> result = JdbcUtil.queryForList(sql, null, AiDataEntity.class);
        ArrayList<AiDataEntity> list = new ArrayList<>();
        if(result == null){
            return list;
        }
        for(AiDataEntity entity : result){
            entity = isLegitimate(entity);
            list.add(entity);
        }
        return list;
    }


    @Override
    public Map<String, String> findCurrentOne() {
        String sql = "SELECT current_temp,reference_temp,save_power,control_status,risk_value FROM ai_information ORDER BY id DESC LIMIT 0,1";
        Map<String, String> map = JdbcUtil.queryForMap(sql, null);
        return map;
    }

    @Override
    public List<AiDataEntity> findByTime(String startTime, String endTime) {
        String base = "id,collect_time,current_temp,recommend_temp reference_temp";
        StringBuffer sqlBuffer = new StringBuffer("SELECT "+base+" FROM d_recommend_temp ");
        ArrayList<String> paramList = new ArrayList<>();
        sqlBuffer.append("WHERE collect_time BETWEEN ? AND ?");
        paramList.add(startTime);
        paramList.add(endTime);
        String sql = sqlBuffer.toString();
        Object[] params = paramList.toArray();
        return JdbcUtil.queryForList(sql,params,AiDataEntity.class);
    }

    @Override
    public boolean insertHistory(AiDataEntity entity) {
        String sql = "insert into ai_history_info(collect_time,current_temp,reference_temp,ip,power,control_status,risk_value) values (?,?,?,?,?,?,?)";
        String complexData = complex(String.valueOf(entity.getReference_temp()));
        Object[] kk = new Object[7];
        kk[0] = entity.getCollect_time();
        kk[1] = entity.getCurrent_temp();
        kk[2] = complexData;
        kk[3] =entity.getIp();
        kk[4] =entity.getPower();
        kk[5] =entity.getControl_status();
        kk[6] =entity.getRisk_value();
        boolean result = false;
        Integer insert = JdbcUtil.insert(sql, kk);
        if(insert != null && insert > 0){
            result = insertBak(complexData,insert);
            //生成签名
            if(result){
                String sign = SM3Util.convertEncryption(complexData);
                result = insertSign(sign,"ai_history_info",insert);
            }
        }
        return result;
}

@Override
public boolean insertPowerStatus(int control_status) {
    String sql = "insert into ai_powerinfo(control_status,collect_time) values (?,?)";
    Object[] kk = new Object[2];
    kk[0] =control_status;
    kk[1] =new Date();
    boolean result = JdbcUtil.update(sql, kk);
    return result;
}

@Override
public Map<String, String> findCurrentPowerStatus() {
    String sql = "SELECT control_status FROM ai_powerinfo ORDER BY id DESC LIMIT 0,1";
    Map<String, String> map = JdbcUtil.queryForMap(sql, null);
    return map;
}

@Override
public AiDataEntity findLastHistoryData() {
    String sql = "SELECT "+baseColumn+" FROM ai_history_info ORDER BY id DESC LIMIT 0,1";
    AiDataEntity entity = JdbcUtil.queryForBean(sql, null, AiDataEntity.class);
    if(entity == null){
        return null;
    }
    return isLegitimate(entity);
}

@Override
public  Map<String, String>  usedServerAmount() {
    String sql="SELECT COUNT(1) as count from device_common WHERE usage_status in(?,?,?) and status=1 and type= ?";
    Object[] kk = new Object[4];
    kk[0] ="running";
    kk[1] ="capping";
    kk[2] ="free";
    kk[3] =server;
    Map<String, String> map = JdbcUtil.queryForMap(sql, kk);
    return map;
}

@Override
public Map<String, String> totalServerAmount() {
    String sql="SELECT COUNT(1) as count from device_common where status= ? and type= ?";
    Object[] kk = new Object[2];
    kk[0] =1;
    kk[1] =server;
    Map<String, String> map = JdbcUtil.queryForMap(sql,kk);
    return map;
}

    @Override
    public List<Map<String, String>> listPowerInfoByCondition(String deviceSn, Integer count) {
        String sql="SELECT id,server_power,inlet_temp,outlet_temp,collect_time,server_sn from state_grid_collect_info where server_sn = ? order by id desc limit ?";
        Object[] kk = new Object[2];
        kk[0] =deviceSn;
        kk[1] =count;
        List<Map<String, String>> map = JdbcUtil.queryForList_Map(sql, kk);
        return map;
    }

    @Override
    public Map<String, String> findAllServerSn() {
        String sql="SELECT  group_concat(device_id) as device_id from device_common WHERE usage_status in(?,?,?) and status=1 and type= ?";
        Object[] kk = new Object[4];
        kk[0] ="running";
        kk[1] ="capping";
        kk[2] ="free";
        kk[3] =server;
        Map<String, String> map = JdbcUtil.queryForMap(sql, kk);
        return map;
    }
    @Override
    public Map<String, String> findCurrentAirTempCollectInfo() {
        String sql="SELECT room_temperature from data_air_dynamic order by id desc limit 1";
        Map<String, String> map = JdbcUtil.queryForMap(sql,null);
        return map;
    }

    public String findBakByID(Integer id) {
        String sql = "select reference_temp from ai_history_info_bak where 1= ? and id=?";
        Integer[] kk = new Integer[2];
        kk[0] = 1;
        kk[1] = id;
        Map<String, String> map = JdbcUtil.queryForMap(sql, kk);
        if(map != null){
            return map.get("reference_temp");
        }
        return null;
    }

    public AiDataEntity isLegitimate(AiDataEntity entity){
        String referenceTemp = entity.getReference_temp();
        //验证是否被篡改
        String checkString = getSign(String.valueOf(entity.getId()));
        String checkString1 = SM3Util.convertEncryption(referenceTemp);
        if(checkString == null){
            return entity;
        }
        if(!checkString.equals(checkString1)) {
            Integer id = entity.getId();
            String s = findBakByID(id);
            if(s == null){
                return null;
            }
            referenceTemp = s;
            boolean b = replace(s,id);
            if(!b){
                return null;
            }
        }
        //解密
        referenceTemp = simplify(referenceTemp);
        entity.setReference_temp(referenceTemp);
        return entity;
    }

    public String complex(String param){
        try {
            param = SM4Util.encrypt_CBC2(param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return param;
    }

    public String simplify(String param){
        try {
            param = SM4Util.decrypt_CBC2(param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return param;
    }

    private boolean insertBak(String reference_temp,int id) {
        String sql = "insert into ai_history_info_bak(id,reference_temp) values (?,?)";
        Object[] kk = new Object[2];
        kk[0] = id;
        kk[1] = reference_temp;
        boolean result = JdbcUtil.update(sql, kk);
        return result;
    }

    public boolean replace(String reference_temp,int id) {
        String sql = "update ai_history_info set reference_temp=? where id=?";
        Object[] kk = new Object[2];
        kk[0] = reference_temp;
        kk[1] = id;
        boolean result = JdbcUtil.update(sql, kk);
        return result;
    }

    public boolean insertSign(String sign, String schemaName, int id) {
        String sql = "insert into data_sign(schemaName,dataId,sign) values(?,?,?)";
        Object[] kk = new Object[3];
        kk[0] = schemaName;
        kk[1] = id;
        kk[2] = sign;
        boolean result = JdbcUtil.update(sql, kk);
        return result;
    }

    public String getSign(String dataId){
        String sql = "select *  from data_sign where dataId=? and schemaName=?";
        Object[] kk = new Object[2];
        kk[0] = dataId;
        kk[1] = "ai_history_info";
        DataSign dataSign = JdbcUtil.queryForBean(sql, kk, DataSign.class);
        if(dataSign != null){
            return dataSign.getSign();
        }
        return null;
    }

    @Override
    public int getCountAirSiteBasal() {
        String sql="select count(distinct location_id) as total from device_common where  type ='air' and status=1 ";
        Map<String, String> map = JdbcUtil.queryForMap(sql.toString(), null);
        if(map == null || map.get("total") == null){
            return 0;
        }
        return Integer.parseInt(map.get("total"));
    }

    @Override
    public List<AirSiteBasalData> getCountAirSiteBasalList(int start, int pageSize) {
        StringBuffer buffer = new StringBuffer("select location_id,device_model from  device_common  " +
            " where  type ='air' and status=1 ");
        ArrayList<Object> list = new ArrayList();
        buffer.append(" group by location_id   ");
        buffer.append(" limit ?,?");
        list.add(start);
        list.add(pageSize);
        Object[] kk = list.toArray();
        List<AirSiteBasalEntity> result = JdbcUtil.queryForList(buffer.toString(),kk, AirSiteBasalEntity.class);
        List<AirSiteBasalData> airSiteBasalDataList = new ArrayList();
        if(result==null || result.size()<=0){
            return null;
        }
        for(AirSiteBasalEntity airSiteBasalEntity:result){
            AirSiteBasalData.Builder airSiteBasalDataBuilder = AirSiteBasalData.newBuilder();
            airSiteBasalDataBuilder.setLocatedU(airSiteBasalEntity.getLocation_id());
            airSiteBasalDataBuilder.setDeviceModel(airSiteBasalEntity.getDevice_model());
            airSiteBasalDataList.add(airSiteBasalDataBuilder.build());
        }
        return airSiteBasalDataList;
    }
}
